package com.mselivanov.vf5android;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CharactersAdapter extends BaseAdapter {
	
	private LayoutInflater inflater;
	
	public CharactersAdapter(Context context) {
		inflater = LayoutInflater.from(context);
		loadIcons(context);
	}

	@Override
	public int getCount() {
		return Characters.NAMES.length;
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.list_item_icon_text, null);
			
			holder = new ViewHolder();
			holder.text = (TextView) convertView.findViewById(R.id.text);
			holder.icon = (ImageView) convertView.findViewById(R.id.icon);
			
			convertView.setTag(holder);
		}
		else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		holder.text.setText(Characters.NAMES[position]);
		holder.icon.setImageBitmap(icons[position]);
		
		return convertView;
	}

	// load character icons
	private void loadIcons(Context context) {
		for (int i = 0; i < Characters.ICON_NAMES.length; i++) {
			int imageResource = context.getResources().getIdentifier(
					"drawable/" + Characters.ICON_NAMES[i], 
					null, 
					context.getPackageName());
			
			icons[i] = BitmapFactory.decodeResource(
					context.getResources(), imageResource);
		}
	}

	static class ViewHolder {
		TextView text;
		ImageView icon;
	}
	
	private Bitmap[] icons = new Bitmap[Characters.NAMES.length];

}
